#include "fenetre.hpp"

Fenetre::Fenetre()
{
	QVBoxLayout *layout = new QVBoxLayout();
	
	QHBoxLayout *lPort = new QHBoxLayout();
	QLabel *labelPort = new QLabel("Port :");
	port = new QSpinBox();
		port->setMinimum(10000);
		port->setMaximum(65535);
	
	QHBoxLayout *lMouvements = new QHBoxLayout();
	QLabel *labelMouvements = new QLabel("Mouvements MAX :");
	mouvements = new QSpinBox();
		mouvements->setMinimum(1);
		mouvements->setMaximum(20);
	
	QHBoxLayout *lClients = new QHBoxLayout();
	QLabel *labelClients = new QLabel("Nombre de clients MAX :");
	clients = new QSpinBox();
		clients->setMinimum(1);
		clients->setMaximum(20);
		
	QHBoxLayout *lHistorique = new QHBoxLayout();
	QLabel *labelHistorique = new QLabel("Nombre de mouvements avant effacement :");
	historique = new QSpinBox();
		historique->setMinimum(1);
		historique->setMaximum(10);
	
	lancer = new QPushButton("Lancer");
	
	lPort->addWidget(labelPort);
	lPort->addWidget(port);
	lMouvements->addWidget(labelMouvements);
	lMouvements->addWidget(mouvements);
	lClients->addWidget(labelClients);
	lClients->addWidget(clients);
	lHistorique->addWidget(labelHistorique);
	lHistorique->addWidget(historique);
	
	QLabel *labelLog = new QLabel("Log :");
	log = new QTextEdit();
		log->setReadOnly(true);
	
	layout->addLayout(lPort);
	layout->addLayout(lMouvements);
	layout->addLayout(lClients);
	layout->addLayout(lHistorique);
	layout->addWidget(labelLog);
	layout->addWidget(lancer);
	layout->addWidget(log);
	
	setLayout(layout);
	
	p = new QProcess();
	connect(lancer,SIGNAL(clicked()),this,SLOT(slotLancer()));
	connect(p,SIGNAL(readyRead()),this,SLOT(slotLire()));
	connect(p,SIGNAL(readyReadStandardError()),this,SLOT(slotErreur()));
}

void Fenetre::slotLancer()
{
	lancer->setEnabled(false);
	
	QString program = "../server/serveur";
	
	QFile f(program);
	if (!f.exists())
	{
		QMessageBox::critical(this, "ERREUR", "Pensez a d'abord compiler le serveur sans interface. Il doit etre present dans \"../server/\"");
		close();
	}
	
	QStringList arguments;
	arguments << QString::number(port->value()) << QString::number(mouvements->value())
	<< QString::number(clients->value()) << QString::number(historique->value());

	p->start(program,arguments);
}

void Fenetre::slotLire()
{
	log->append(p->readAll());
}

void Fenetre::slotErreur()
{
	QString e;
	e = "<span style=\"color : red\">ERREUR : <br/> " + p->readAllStandardError() + "</span>";
	log->append(e);
}

void Fenetre::closeEvent(QCloseEvent *event)
{
	p->write("q\n");
}
